﻿using Knife.Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Knife.Core.DataBase
{
    public class SQLBuilder
    {
        public static string BuildInsertSQL<T>()
        {
            MapperEntity map = EntityMapper.GetInstance().GetMapperEntity(typeof(T));
            StringBuilder buildsql = new StringBuilder();
            buildsql.AppendFormat("insert into {0}", map.MapTableName);
            //字段
            string fieldsstr = string.Empty;
            //值
            string valuestr = string.Empty;
            fieldsstr += " (";
            valuestr += " values(";
            foreach (var item in map.ColumnMapDic)
            {
                fieldsstr += item.Value + ",";
                valuestr += string.Format("@{0}", item.Value) + ",";
            }
            fieldsstr = fieldsstr.TrimEnd(',') + " )";
            valuestr = valuestr.TrimEnd(',') + " )";
            buildsql.Append(fieldsstr).Append(valuestr);
            return buildsql.ToString();
        }
        public static string BuildDeleteSQL<T>()
        {
            MapperEntity map = EntityMapper.GetInstance().GetMapperEntity(typeof(T));
            return string.Format("delete from {0} where {1}=@{1}", map.MapTableName, map.MapTableID);
        }
        public static string BuildUpdateSQL<T>() where T : BaseEntity
        {
            MapperEntity map = EntityMapper.GetInstance().GetMapperEntity(typeof(T));
            StringBuilder buildsql = new StringBuilder();
            buildsql.AppendFormat("update {0} set ", map.MapTableName);
            string tempstr = string.Empty;
            foreach (var item in map.ColumnMapDic)
            {
                tempstr += string.Format("{0}=@{0},", item.Value);
            }
            tempstr = tempstr.TrimEnd(',');
            buildsql.Append(tempstr);
            buildsql.AppendFormat(" where {0}=@{0}", map.MapTableID);
            return buildsql.ToString();
        }
    }
}
